<?php

namespace app\index\controller;

use think\Controller;
use Okx;
use think\exception\ThrowableError;

class Index extends Base
{
    public function index()
    {
        // for($i = 0; $i < 50; $i ++) {
        // $roll [$i] ['user_name'] = randomkeys ( 2 ) . '***';
        // $roll [$i] ['money'] = mt_rand ( 500, 49999 );
        // $roll [$i] ['type'] = mt_rand ( 0, 1 ) == 0 ? lang('recharge') : lang('withdraw');
        // $roll [$i] ['create_time'] = time () - mt_rand ( 500, 5000 );
        // }
        // $this->assign ( 'roll', array_sort ( $roll, 'create_time', 'desc' ) );

        // $key = '1af61d2c-0949-491a-91c1-123d83c57d19';
        // $secret = 'F421319CDF46AE1705FCC4B09D3CCCD9';
        // date_default_timezone_set ( "UTC" );
        // $okx = new \Okx ( $key, $secret );
        // $method = 'GET';
        // $path = '/api/v5/market/tickers';
        // $times = str_replace ( '+00:00', 'Z', gmdate ( 'c' ) );
        // $pwd = 'Uu888888..';

        // $data ['instType'] = 'SWAP';

        // $str = $times . $method . $path . json_encode ( $data );
        // $sign = $okx->sign ( $str );
        // $headers = $okx->header ( $key, $sign, $times, $pwd );
        // // $result = $okx->curl_post ( 'https://www.okx.com/api/v5/market/tickers?instType=SWAP', '', $headers );
        // $result = file_get_contents ( 'okx.json' );
        // $result = json_decode ( $result, true );
        // unset ( $data );
        // if ($result ['code'] == 0) {
        // $data = $result ['data'];
        // $coin = array ('BTC-USDT-SWAP','ETH-USDT-SWAP','DOGE-USDT-SWAP','EOS-USDT-SWAP','LTC-USDT-SWAP','BCH-USDT-SWAP','XRP-USDT-SWAP','ETC-USDT-SWAP','BSV-USDT-SWAP','XMR-USDT-SWAP','DOT-USDT-SWAP','ADA-USDT-SWAP','FIL-USDT-SWAP','TRX-USDT-SWAP','UNI-USDT-SWAP','LINK-USDT-SWAP','SOL-USDT-SWAP','AAVE-USDT-SWAP','HT-USDT-SWAP' );
        // $i = 0;
        // foreach ( $data as $k => $v ) {
        // if (in_array ( $v ['instId'], $coin )) {
        // $instId = explode ( '-', $v ['instId'] );
        // $dt [$i] = $v;
        // $dt [$i] ['instId0'] = $instId [0];
        // $dt [$i] ['instId1'] = $instId [1];
        // $dt [$i] ['instId2'] = $instId [2];
        // $i ++;
        // }
        // }
        // }

        // $key = 'KI6TXIA5AEBSWRRW9IJIMIFGVWMQ9QIRKIAYCP7B';
        // $mf = new \Mifengcha ( $key );
        // $path = '/api/v3/tickers';
        // $result = $mf->curl_post ( $path, array ('market' => 'binance' ) );
        // $result = json_decode ( $result, true );
        // unset ( $data );
        // if (count ( $result ) > 0) {
        // foreach ( $result as $k => $v ) {
        // $instId = explode ( '_', $v ['m'] );
        // $result [$k] ['instId0'] = $instId [0];
        // $result [$k] ['instId1'] = $instId [1];
        // $result [$k] ['instId2'] = $instId [2];
        // }
        // }
        // $this->assign ( 'okx', $dt );
        return $this->fetch();
    }

    function upload()
    {
        define('WEB_ROOT', dirname(__FILE__));
        $img = $_POST ['img'];
        list ($type, $data) = explode(',', $img);
        if (strstr($type, 'image/jpeg') != '') {
            $ext = '.jpg';
        } elseif (strstr($type, 'image/gif') != '') {
            $ext = '.gif';
        } elseif (strstr($type, 'image/png') != '') {
            $ext = '.png';
        } else
            die(json_encode(array('code' => 0)));
        $dirname = date('Ymd');
        if (!is_dir(WEB_ROOT . '/../../../public/attached/' . $dirname)) {
            mkdir(WEB_ROOT . '/../../../public/attached/' . $dirname);
        }
        $filename = $dirname . '/' . time() . rand(000, 999) . $ext;
        $data = str_replace(' ', '+', $data);
        $path = WEB_ROOT . '/../../../public/attached/' . $filename;
        $res = file_put_contents($path, base64_decode($data, true));
        // $res = file_put_contents ( 'F:/wwwroot/obu/attached/' . $filename, $img );
        if (file_exists($path))
            echo json_encode(array('code' => 99, 'result' => $filename));
        else
            echo json_encode(array('code' => 0));
    }

    function lang()
    {
        return $this->fetch();
    }

    /*
     * 支付回调
     *
     * 参数名	含义	类型	说明
        appid	APPID	string(16)	商户唯一识别码
        type	通知类型	string(16)	固定=issue
        success_count	打款成功的条数	int(11)
        fail_count	打款失败的条数	int(11)
        task_id	任务ID	string(20)
        signature	签名	string(32)	安全校验签名串
        list[n].status	打款状态	int(1)	1=提交成功（打款中），2=打款成功（打款完成），0=失败
        list[n].order_num	打款订单号	string(32)
        list[n].hash	打款的hash	string(100)	打款成功才有值
        list[n].address	下发地址	string(100)
        list[n].amount	下发金额	string(16
     *
     * */
    public function callback() {
        $parma = $this->request->param();
        $type =$parma['type'];
        $money = $parma ['money'];
        $UPApiConfig = get_config();
        $paymentApi = new Upapi($UPApiConfig);
        $sign = $parma['signature'];
        unset($parma['signature']);
        $signature = $paymentApi->createSign($parma);

        if ($sign !== $signature){
            $log = [
                'parma' => $parma,
               'msg' => '签名错误!',
            ];
            logger('callback', $log);
            return;
        }

        if ($type == 'order'){
            try {

                $t_order_num= $this->request->param('t_order_num');
                $shop_user_id= $this->request->param('user_id');
                if (empty($t_order_num)){
                    $recharge= model('Recharge')->where(['shop_user_id' => $shop_user_id,'status' => 1])->find()->toArray();
                }else{
                    $recharge= model('Recharge')->where(['t_order_num' => $t_order_num,"status"=>1])->find()->toArray();
                }

                $status = 2; // 默认成功
                if ($recharge) {
                    if ( $money > 0 && empty($t_order_num)){
                        $status = 3; //未足额3
                    }
                    $recharge['status'] = $status;
                    $recharge['pay_money'] = $money;
                    $recharge['order_num'] = $parma['order_num'];
                    $recharge['update_time'] = time();
                    $log = [
                        'recharge' => $recharge,
                        'parma' => $parma,
                        'msg' => '修改订单状态!',
                    ];
                    logger('callback', $log);
                    $res = model('Recharge')->save($recharge, ['t_order_num' => $t_order_num]);

                    if ($res > 0) {
                        if ( $money > 0) {
                            $info = model ( 'Member' )->getInfo ( array ([ 'user_id','=',$recharge['user_id'] ] ) );
                            model ( 'Member' )->incMoney ( array ([ 'user_id','=',$info ['user_id'] ] ), $money );
                            unset ( $data );
                            $data ['user_id'] = $info['user_id'];
                            $data ['money'] = $money;
                            $data ['create_time'] = time ();
                            $data ['type'] = 1;
                            $data ['before_money'] = $info ['money'];
                            $data ['after_money'] = $info ['money'] + $money;
                            $data ['remark'] = 'recharge';
                            model ( 'Member' )->addMoneyLog ( $data );
                        }
                        $log = [
                            'data' => $data,
                            'msg' => '用户余额修改!',
                        ];
                        logger('callback', $log);
                    }
                }else{
                    $log = [
                        'error'=>'无订单号!',
                        'data'=>$parma,
                    ];
                    logger('callback', $log);
                }
                echo "__SUCCESS__";

            }catch (ThrowableError $e){
               $msg = [
                   'msg'=>$e->getMessage(),
               ];
               logger('callback', $msg);
               echo "__FAIL__";
            }

        }
    }

}
